########################################################################
# PLS 206 — Week 6 live coding, part 1: shrinkage
# Grey Monroe, Fall 2026
########################################################################

# install.packages(c("lme4", "lmerTest", "glmnet", "ggplot2"))
library(lmerTest)   # loads lme4 too, and adds p-values to lmer()
library(glmnet)
library(ggplot2)

########################################################################
# Plotting helpers (run this block once; no need to read it in class)
########################################################################

# raw data + the average farm's fitted line and 95% CI (fixed effects only)
# farm_lines = TRUE adds each farm's own fitted line from the mixed model
plot_fit <- function(m, data, x, y, farm_lines = FALSE) {
  g <- data.frame(seq(min(data[[x]]), max(data[[x]]), length.out = 100)); names(g) <- x
  for (v in setdiff(all.vars(formula(m, fixed.only = TRUE))[-1], x)) g[[v]] <- data[[v]][1]
  X <- model.matrix(delete.response(terms(formula(m, fixed.only = TRUE))), g)
  eta <- drop(X %*% fixef(m)); se <- sqrt(rowSums((X %*% as.matrix(vcov(m))) * X))
  inv <- if (isGLMM(m)) family(m)$linkinv else identity
  g$fit <- inv(eta); g$lo <- inv(eta - 1.96 * se); g$hi <- inv(eta + 1.96 * se)
  p <- ggplot(data, aes(.data[[x]], .data[[y]], colour = farm))
  if (isGLMM(m)) p <- p + geom_jitter(height = 0.03, width = 0, alpha = 0.6) else p <- p + geom_point(alpha = 0.7)
  if (farm_lines) p <- p + geom_line(aes(y = fitted(m)), linewidth = 0.5)
  p + geom_ribbon(data = g, aes(x = .data[[x]], ymin = lo, ymax = hi), inherit.aes = FALSE, alpha = 0.25, fill = "steelblue") +
    geom_line(data = g, aes(.data[[x]], fit), inherit.aes = FALSE, colour = "steelblue4", linewidth = 1.3) +
    theme_classic() + theme(legend.position = "none")
}

# each farm's yield at 100 kg N: its own plots only (lm) vs the mixed model
plot_shrinkage <- function(m_fixed, m_mixed, data) {
  d <- data.frame(farm = sort(unique(data$farm)), nitrogen = 100)
  d$plots <- as.numeric(table(data$farm)[d$farm])
  d$own <- predict(m_fixed, d); d$mixed <- predict(m_mixed, d)
  d$farm <- reorder(paste0(d$farm, " (", d$plots, " plots)"), d$plots)
  ggplot(d, aes(y = farm)) +
    geom_vline(xintercept = fixef(m_mixed)[1] + fixef(m_mixed)[2] * 100, linetype = 2, colour = "grey50") +
    geom_segment(aes(x = own, xend = mixed), arrow = arrow(length = unit(0.15, "cm")), colour = "purple") +
    geom_point(aes(x = own), shape = 1, size = 3) + geom_point(aes(x = mixed), colour = "purple", size = 3) +
    labs(x = "Yield at 100 kg N/ha (t/ha): open = own plots only, purple = mixed model", y = NULL) + theme_classic()
}

# glmnet coefficient paths with the predictor names on the lines
plot_path <- function(fit) {
  b <- as.matrix(coef(fit))[-1, ]
  d <- data.frame(predictor = rep(rownames(b), ncol(b)), log_lambda = rep(log(fit$lambda), each = nrow(b)), slope = c(b))
  ends <- d[d$log_lambda == min(d$log_lambda), ]
  ends <- ends[order(-abs(ends$slope)), ][1:5, ]     # label the 5 biggest
  ggplot(d, aes(log_lambda, slope, colour = predictor)) + geom_hline(yintercept = 0, colour = "grey60") + geom_line() +
    geom_text(data = ends, aes(label = predictor), hjust = 1.05, size = 3, show.legend = FALSE) +
    scale_x_reverse() + guides(colour = "none") +
    labs(x = "log(lambda)  (bigger penalty to the left)", y = "Slope (kg/ha per SD)") + theme_classic()
}

########################################################################
# 1. The data: 112 plots on 12 farms
########################################################################

farms <- read.csv("https://greymonroe.github.io/PLS_206/data/farm_plots.csv")
head(farms)
table(farms$farm)                     # 2 to 25 plots per farm

########################################################################
# 2. Yield and nitrogen, with farm as a random effect
########################################################################

m_mixed <- lmer(yield ~ nitrogen + (1 | farm), data = farms)
summary(m_mixed)                      # nitrogen: p < 0.001, df about 105
VarCorr(m_mixed)                      # farm-to-farm SD 0.76, plot-to-plot SD 1.08

plot_fit(m_mixed, farms, "nitrogen", "yield") +
  labs(x = "Nitrogen (kg N/ha)", y = "Yield (t/ha)")

########################################################################
# 3. Shrinkage: each farm on its own vs the mixed model
########################################################################

m_fixed <- lm(yield ~ nitrogen + farm, data = farms)
plot_shrinkage(m_fixed, m_mixed, farms)    # farms with few plots move the most

########################################################################
# 4. Cover crops: chosen per farm, not per plot
########################################################################

m_plots <- lm(yield ~ nitrogen + cover, data = farms)
summary(m_plots)                      # cover p < 0.001: treats 112 plots as independent

m_cover <- lmer(yield ~ nitrogen + cover + (1 | farm), data = farms)
summary(m_cover)                      # cover p = 0.43, df about 8: 12 farms, not 112 plots

########################################################################
# 5. Do farms respond to nitrogen differently? Random slopes
########################################################################

farms$n100 <- farms$nitrogen / 100    # per 100 kg N, so lmer converges
m_int   <- lmer(yield ~ n100 + (1 | farm), data = farms)
m_slope <- lmer(yield ~ n100 + (n100 | farm), data = farms)
anova(m_int, m_slope, refit = FALSE)  # yes: chi-squared 17.6, p < 0.001

plot_fit(m_slope, farms, "n100", "yield", farm_lines = TRUE) +
  labs(x = "Nitrogen (100 kg N/ha)", y = "Yield (t/ha)")    # thin lines: each farm's own (shrunk) line

########################################################################
# 6. Rust (yes/no): glmer
########################################################################

m_rust <- glmer(rust ~ nitrogen + (1 | farm), data = farms, family = binomial)
summary(m_rust)
exp(10 * fixef(m_rust)["nitrogen"])   # odds of rust x1.16 per 10 kg N

plot_fit(m_rust, farms, "nitrogen", "rust") +
  labs(x = "Nitrogen (kg N/ha)", y = "Probability of rust")

# checks: residuals vs fitted, and the farm effects should look roughly normal
plot(m_mixed)
qqnorm(ranef(m_mixed)$farm[, 1]); qqline(ranef(m_mixed)$farm[, 1])

########################################################################
# 7. Ridge and lasso: the cover-crop farms from Week 5
########################################################################

cc <- read.csv("https://greymonroe.github.io/PLS_206/data/cover_crop.csv")
X <- scale(as.matrix(subset(cc, select = -c(farm, biomass, clay))))  # 15 predictors in SD units
                                      # (clay left out: sand + silt + clay = 100)
y <- cc$biomass                       # kg/ha

fit_ridge <- glmnet(X, y, alpha = 0)
plot_path(fit_ridge)                  # every slope shrinks, none hits zero

fit_lasso <- glmnet(X, y, alpha = 1)
plot_path(fit_lasso)                  # slopes hit zero one by one; gdd lasts
coef(fit_lasso, s = 300)              # only gdd left
coef(fit_lasso, s = 50)               # a smaller penalty: more predictors in
